package com.tjetc.util;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class JwtUtils {
    //	自定义秘钥
    private static final String secret = "123123";
    //	jwtToken的默认有效时间
    private static final int expireTime = 1000 * 60 * 60 * 24;

    public static String createJwtToken(Map<String, Object> map) {
        JwtBuilder builder = Jwts.builder();
        String token = builder
                //header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //payload
                .setClaims(map)
                .setSubject("test")
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        return token;
    }

    //	从令牌中获取数据,就是payLoad部分存放的数据.如果jwt被改,该方法会直接抛出异常
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    public static boolean checkToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return false;
    }
}